package com.example.demo.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.converter.UserConverter;
import com.example.demo.dto.PageRequest;
import com.example.demo.dto.UserDto;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@CacheConfig(cacheNames = "users::xxxx:yyy:zzz")// redis namespace
public class UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserAsyncService userAsyncService;

    /**
     * 1. 首先查缓存，是否存在users::{id}
     * 2.1. 如果查得到，则从缓存返回，不执行此方法的方法体；
     * 2.2. 如果查不到，则执行此方法
     * <p>
     * spel
     *
     * @param id
     * @return
     */
    @Cacheable(key = "#id")
    public User findById(Integer id) {
        return this.userMapper.selectById(id);
    }

    public void doBiz(){
        // insert 50ms
        // 查询用户信息  100ms

        // 3s 记录日志
        userAsyncService.asyncVoid();
    }

    @Transactional(rollbackFor = Exception.class)
    public List<UserDto> search(PageRequest<UserDto> req) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        UserDto condition = req.getCondition();
//        if (condition.getId() != null) {
//            wrapper.eq("id", condition.getId());
//        }
        if (StringUtils.isNotBlank(condition.getName())) {
            wrapper.eq("username", condition.getName());
        }
        return this.userMapper.selectList(new Page<>(req.getPageNo(), req.getPageSize()), wrapper)
                .stream()
                .map(UserConverter.C::toDto)
                .collect(Collectors.toList());
    }
}

/**
 * spring mvc controlleradvice        ==> 特别
 * spring 事务
 * spring 缓存
 * spring aop this指针问题
 */
